package com.wswy.wzcx.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.che.libcommon.ui.VOMessage;
import com.che.libcommon.ui.loading.LoadingFragment;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.Genre;
import com.wswy.wzcx.model.GenreChild;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.activity.AddBillActivity;
import com.wswy.wzcx.ui.adapter.GenreAdapter;
import com.wswy.wzcx.ui.other.ChildClickListener;
import com.wswy.wzcx.ui.persenter.BookKeepPresenter;
import com.wswy.wzcx.ui.view.BookKeepView;
import java.util.ArrayList;
import java.util.List;

/**
 * 养车账本
 */
public class BookKeepingFragment extends LoadingFragment implements View.OnClickListener, ChildClickListener, BookKeepView {
    public static final String TAG = "BookKeepingFragment";
    public static final int RQ_ADD = 0X101;
    RecyclerView recyclerView;
    View btnAdd;
    TextView tvTop;
    CollapsingToolbarLayout layout;

    private List<Genre> list;
    private String topString = "";
    private BookKeepPresenter presenter;
    GenreAdapter adapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        presenter = new BookKeepPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_nav_bookkeeping, container, false);
//        StatusBarCompat.setup(inflate);
        presenter.setUpStatusBar(inflate);
        return inflate;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = view.findViewById(R.id.recycler_view);
        btnAdd = view.findViewById(R.id.btn_add);
        tvTop = view.findViewById(R.id.tv_top);
        layout = view.findViewById(R.id.collapsing_layout);

        ViewCompat.setElevation(btnAdd, 20);
    }

    @Override
    public void onResume() {
        super.onResume();
        StatTools.sendPageStart(getContext(),TAG);
    }

    @Override
    public void onPause() {
        super.onPause();
        StatTools.sendPageEnd(getContext(),TAG);
    }

    @Override
    protected int getLoadingFrameId() {
        return R.id.recycler_view;
    }

    @Override
    protected int getLoadingRootId() {
        return R.id.layout_loading_root;
    }

    @Override
    public LoadingConfigure getConfigure() {
        return null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            Paint mPaint = new Paint();

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
                mPaint.setStyle(Paint.Style.FILL);
                mPaint.setColor(Color.parseColor("#e6e6e6"));
                for (int i = 0; i < parent.getChildCount(); i++) {
                    View view = parent.getChildAt(i);
                    c.drawRect(view.getLeft(), view.getBottom(), view.getRight(), view.getBottom() + 1, mPaint);
                }
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                final RecyclerView.Adapter adapter = parent.getAdapter();
                if (adapter != null && parent.getChildAdapterPosition(view) == adapter.getItemCount() - 1) {
                    outRect.bottom = 0;
                } else {
                    outRect.bottom = 1;
                }
            }
        });
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof DefaultItemAnimator) {
            ((DefaultItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        list = new ArrayList<>();
        btnAdd.setOnClickListener(this);
        presenter.onCreate(getArguments());
        setup();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (presenter != null) presenter.onDestroy();
    }

    private void setup() {
        if (presenter.hasLogin()) {
            presenter.setup();
            showLoading(false);
            hideLoginView();
        } else {
            showLoginView();
        }

    }

    @Override
    public void onClick(View v) {
        startActivityForResult(new Intent(getContext(), AddBillActivity.class), RQ_ADD);
        StatTools.sendClick(getContext(), StatisticsId.clickAddBillInBill);
    }

    @Override
    public void onClick(View v, GenreChild tag) {
        startActivityForResult(AddBillActivity.asIntent(v.getContext(), tag), RQ_ADD);
        StatTools.sendClick(getContext(), StatisticsId.clickItemBillInBill);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RQ_ADD && resultCode == Activity.RESULT_OK) {
            presenter.setup();
        }
    }

    @Override
    public Activity activity() {
        return getActivity();
    }

    @Override
    public void setTopString(String str) {
        topString = str;
    }


    @Override
    public void onSuccess(List<Genre> genres) {
        list.clear();
        list.addAll(genres);
        if (list.isEmpty()) {
            setTextMsgStyle(0,R.style.bill_empty_desc);
            showError(VOMessage.createEmpty(R.drawable.bill_default, R.string.empty_bill,R.string.empty_bill_try, 0));
        } else {
            showData();
            adapter = (GenreAdapter) recyclerView.getAdapter();
            if (adapter == null) {
                adapter = new GenreAdapter(list);
                adapter.setChildClickListener(BookKeepingFragment.this);
                recyclerView.setAdapter(adapter);
            } else {
                adapter.changed();
            }
        }
        tvTop.setText(topString);
        tvTop.post(new Runnable() {
            @Override
            public void run() {
                int childCount = recyclerView.getChildCount();
                int visibleItemCount = adapter != null ? adapter.getVisibleItemCount() : 0;
                setCollaps(childCount != visibleItemCount);
            }
        });
    }

    @Override
    public void showLoginView() {
        View view = getView();
        if (view != null) {
            View flLoginView = view.findViewById(R.id.fl_login_view);
            flLoginView.setVisibility(View.VISIBLE);
            View btnLogin = view.findViewById(R.id.btn_login);
            btnLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(RouterUtils.getLogin());
                }
            });
        }
    }

    @Override
    public void hideLoginView() {
        View view = getView();
        if (view != null) {
            presenter.setUpStatusBar(view);
            View flLoginView = view.findViewById(R.id.fl_login_view);
            flLoginView.setVisibility(View.GONE);
        }
    }

    private void setCollaps(boolean flag) {
        ViewGroup.LayoutParams layoutParams = layout.getLayoutParams();
        if (layoutParams instanceof AppBarLayout.LayoutParams) {
            int scrollFlags = flag ? AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL : AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP;
            ((AppBarLayout.LayoutParams) layoutParams).setScrollFlags(scrollFlags);
        }
    }

    @Override
    public String getFragmentTitle() {
        return "养车账本";
    }
}
